/*
 * 
 * Raj Akula	
 * Inventory Look Up Android Application
 * CSC 594
 * 
 * InventoryLookUpActivity
 * Adds items to database and deletes items to database activity. 
 * 
 */

package nku.csc594.project3;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class InventoryLookUpActivity extends Activity {
		private Spinner categorySpinner;
		private Spinner itemSpinner;
		private EditText itemNumber;
		private EditText quantity;
		private EditText price;
		private ImageView imgView;
		private int imageViewID = -1;
		DataHelper db = null;
		
		private Integer[] Imgid = {
				R.drawable.proj3_1, 
				R.drawable.proj3_2, 
				R.drawable.proj3_3, 
				R.drawable.proj3_4, 
				R.drawable.proj3_5, 
				R.drawable.proj3_6, 
				R.drawable.proj3_7,
				R.drawable.proj3_8,
				R.drawable.proj3_9,
				R.drawable.proj3_10,
				R.drawable.proj3_11,
				R.drawable.proj3_12,
				R.drawable.proj3_13,
				R.drawable.proj3_14 
				};
		
		
	  public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.inventorylookup);  
	        categorySpinner = (Spinner)findViewById(R.id.spinner1);
	        itemSpinner = (Spinner)findViewById(R.id.spinner2);
	        itemNumber = (EditText)findViewById(R.id.editText1);
	        quantity = (EditText)findViewById(R.id.editText2);
	        price = (EditText)findViewById(R.id.editText3);
	        imgView = (ImageView)findViewById(R.id.imageView1);
	        setCategorySpinner();
	        db = new DataHelper(this);
	        setItemSpinner();
	        itemSpinner.setPrompt("Select...");
	        itemSpinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
	  }
	  
	  public ArrayAdapter<CharSequence> getCategoryAdapter(){
		  ArrayAdapter<CharSequence> categoryAdapter = ArrayAdapter.createFromResource(
	                this, R.array.category_array, android.R.layout.simple_spinner_item);
	        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        return categoryAdapter;
	  }
	  
	  public void setCategorySpinner(){
		  categorySpinner.setAdapter(getCategoryAdapter());
	  }
	  
	  @SuppressWarnings("unchecked")
	public ArrayAdapter<CharSequence> getItemAdapter(){
		    @SuppressWarnings("rawtypes")
			ArrayAdapter itemAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, db.selectAll());	 
	        itemAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	        itemAdapter.insert(" ", 0);
	        return itemAdapter;
	  }
	  
	  public void setItemSpinner(){
		  itemSpinner.setAdapter(getItemAdapter());
	  }
	  
	  public class MyOnItemSelectedListener implements OnItemSelectedListener {

		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		    	if(!parent.getItemAtPosition(pos).toString().equals(" ")){
			    	Cursor mCursor = db.getItem(parent.getItemAtPosition(pos).toString());
			    	int i = 0;
					for(String x : mCursor.getColumnNames()){
						if(i == 0){
							String category = mCursor.getString(mCursor
									.getColumnIndexOrThrow(x));
							int position; 
							if(category.equals("Case")){
								position = 0;
							}
							else if(category.equals("CPU")){
								position = 1;
							}
							else if(category.equals("Hard Drive")){
								position = 2;
							}
							else if(category.equals("Keyboard")){
								position = 3;
							}
							else if(category.equals("Memory (RAM)")){
								position = 4;
							}
							else if(category.equals("Monitor")){
								position = 5;
							}
							else if(category.equals("Mother Board")){
								position = 6;
							}
							else if(category.equals("Power Supply")){
								position = 7;
							}
							else{
								position = 0;
							}
							categorySpinner.setSelection(position);
							categorySpinner.setSelection(position, true);
							System.out.println(category);
							
						}
						else if( i == 1){
							String itemNumber1 = mCursor.getString(mCursor
									.getColumnIndexOrThrow(x));
							itemNumber.setText(itemNumber1);
							System.out.println(itemNumber1);
						}
						else if( i == 2){
							Integer qoh = (int)mCursor.getLong(mCursor
									.getColumnIndexOrThrow(x));
							quantity.setText(qoh.toString());
							System.out.println(qoh);
						}
						else if( i == 3){
							Float qoh = (Float)mCursor.getFloat(mCursor
									.getColumnIndexOrThrow(x));
							price.setText(qoh.toString());
							System.out.println(qoh);
						}
						else if( i == 4){
							Integer picNum = (int)mCursor.getLong(mCursor
									.getColumnIndexOrThrow(x));
							setPicture(picNum);
							System.out.println(picNum);
						}
						i++;
					}
			    }
		    	else{
		    		clean();
		    	}
		    }
		    public void onNothingSelected(@SuppressWarnings("rawtypes") AdapterView parent) {
		      // Do nothing.
		    }
	}
	  
	public void doSelectPicture(View view){
			Intent launchSelectPicture = new Intent(this, SelectPictureActivity.class);
			startActivityForResult(launchSelectPicture, 0);
	}
	
	public void doUpdateDelete(View view){
		if(checkDelete()){
			db.delete(this.itemSpinner.getSelectedItem().toString());
			this.setItemSpinner();
		}
		else{
			new AlertDialog.Builder(this)
			.setTitle("Delete Error!!")
			.setMessage("An item should be selected, for a delete.")
			.setNeutralButton("OK", null)
		  		.show();		
			}
	}
	
	public void doDelete(View view){
		if(checkDelete()){
			db.delete(this.itemSpinner.getSelectedItem().toString());
			this.setItemSpinner();
			this.clean();
		}
		else{
			new AlertDialog.Builder(this)
			.setTitle("Delete Error!!")
			.setMessage("An item should be selected, for a delete.")
			.setNeutralButton("OK", null)
		  		.show();		
			} 
	}
	
	private void clean() {
		this.itemNumber.setText("");
		this.price.setText("");
		this.quantity.setText("");
		this.categorySpinner.setSelection(0);
		this.itemSpinner.setSelection(0);
		
	}

	private boolean checkDelete() {
		if(!itemSpinner.getSelectedItem().toString().equals(" ")){
			return true;
		}
		return false;
	}

	public void doAdd(View view){
		if(checkAdd()){
			db.insert(categorySpinner.getSelectedItem().toString(), itemNumber.getText().toString(), Integer.parseInt(quantity.getText().toString()),Float.parseFloat(price.getText().toString()), imageViewID);
			this.setItemSpinner();
			this.clean();
		}
		else{
			new AlertDialog.Builder(this)
			.setTitle("Add Error!!")
			.setMessage("All fields except item, must be filled in(and an image should also be selected), for an add.")
			.setNeutralButton("OK", null)
		  		.show();
			}
	}
	
	private boolean checkAdd() {
		if(this.itemNumber.getText().toString().isEmpty() || 
				this.quantity.getText().toString().isEmpty() ||
				this.price.getText().toString().isEmpty()||
				this.imageViewID == -1){	
			return false;
		}else{			
			return true;
		}
	}

	public void doUpdate(View view){
		if(checkUpdate() && !itemSpinner.getSelectedItem().toString().equals(" ")){
			this.doUpdateDelete(view);
			db.insert(categorySpinner.getSelectedItem().toString(), itemNumber.getText().toString(), Integer.parseInt(quantity.getText().toString()),Float.parseFloat(price.getText().toString()), imageViewID);
			this.setItemSpinner();
			this.clean();
		}
		else{
			new AlertDialog.Builder(this)
			.setTitle("Update Error!!")
			.setMessage("All fields must be filled in(and an image should also be selected), for an update.")
			.setNeutralButton("OK", null)
		  		.show();
		}
	}
	  //etPayRate.getText().toString().isEmpty()
	private boolean checkUpdate() {
		if(this.itemNumber.getText().toString().isEmpty() || 
				this.quantity.getText().toString().isEmpty() ||
				this.price.getText().toString().isEmpty() ||
				this.imageViewID == -1 ||
				!itemSpinner.getSelectedItem().toString().equals(" ")){
			return false;
		}else{			
			return true;
		}
	}

	protected void onActivityResult(int requestCode,int resultCode, Intent data) {
		if (resultCode == RESULT_OK) 
		{
			int pictureID = data.getExtras().getInt("pictureNumber");
			setPicture(pictureID);	
		}
		else{
			Toast
			  .makeText(this, "Picture not passed back!",Toast.LENGTH_LONG)
			  .show();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void setPicture(int pictureID) {
		if(pictureID > -1 && pictureID < 14){
			imgView.setImageResource(Imgid[pictureID]);
			imageViewID = pictureID;
		}
		else{
			Toast
			  .makeText(this, "Picture reference is incorrect!",Toast.LENGTH_LONG)
			  .show();
		}
	}
	  
}
